<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="学科名称" prop="subjectName">
        <el-input
          v-model="queryParams.subjectName"
          placeholder="请输入学科名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 修改删除多选 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:subject:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['exam:subject:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-tooltip
          class="item"
          effect="dark"
          content="导出数据由当前分页数据决定"
          placement="top-start"
        >
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['exam:subject:export']"
            >导出</el-button
          >
        </el-tooltip>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getSubjectList"
      ></right-toolbar>
    </el-row>

    <!-- 数据展示 -->
    <el-table
      :border="true"
      v-loading="loading"
      :data="subjectList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="checkPermi(['exam:question:remove', 'exam:question:export'])"
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column label="主键" align="center" prop="subjectId" />
      <el-table-column label="名称" prop="subjectName">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.subjectName"
            placement="right"
          >
            <span> {{ scope.row.subjectName | ellipsis(0, 5) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column sortable label="排序" align="center" prop="orderNum" />

      <el-table-column
        sortable
        label="创建时间"
        align="center"
        prop="createTime"
      />

      <!--   <el-table-column label="更新时间" align="center" prop="updateTime" /> -->
      <el-table-column
        v-if="checkPermi(['exam:subject:edit'])"
        label="学科状态"
        align="center"
        prop="status"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            @change="handleStatus(scope.row)"
            active-value="0"
            inactive-value="1"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="checkPermi(['exam:subject:edit', 'exam:subject:remove','exam:subject:index'])"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openDrawer(scope.row)"
            v-hasPermi="['exam:subject:index']"
            >查看</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:subject:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            :disabled="ids.length > 0"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['exam:subject:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getSubjectList"
    />

    <!-- 添加或修改学科对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input
            v-model="form.subjectName"
            placeholder="请输入学科名称"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="学科排序" prop="orderNum">
          <el-input-number
            :min="1"
            controls-position="right"
            v-model="form.orderNum"
            placeholder="请输入学科排序"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 所属学科的试题列表 -->
    <el-drawer
      :visible.sync="drawerVisible"
      direction="rtl"
      size="50%"
      title="查看属于该学科的试题"
    >
      <div class="questionList">
        <div class="mb20 ml20 page">
          <el-pagination
            v-show="questionListPage.total > 0"
            background
            :page-sizes="[5, 10, 15, 50]"
            :page-size="questionListPage.pageSize"
            layout="total,sizes,prev, pager, next"
            @current-change="currentChange"
            @size-change="sizeChange"
            :total="questionListPage.total"
          >
          </el-pagination>
        </div>
        <div class="questionItem">
          <el-card class="ml20 mb20" v-for="v in questionList" :key="v.id">
            <question :question="v"></question>
          </el-card>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listSubject,
  getSubject,
  delSubject,
  addSubject,
  updateSubject,
  updateSubjectStatus,
  getQuestionBySubjectId,
} from "@/api/exam/subject";
import question from "@/components/exam/showQuestion/question";
import { checkPermi } from "@/utils/permission"; // 权限判断函数
export default {
  components: { question },
  name: "Subject",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学科表格数据
      subjectList: [],
      // 所属学科的试题列表数据
      questionList: [],
      // 是否显示所属学科的试题列表数据的抽屉
      drawerVisible: false,
      // 所属学科分页参数
      questionListPage: {
        subjectId: null,
        pageNum: 1,
        // 注意这个size要和组件的  :page-sizes="[5, 10, 15, 50]" 第一个一致，否则在默认请求时，会是这个数据，
        pageSize: 5,
        total: 0,
      },

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectName: null,
      },
      // 表单参数
      form: {
        subjectId: null,
        subjectName: null,
        orderNum: null,
      },
      // 表单校验
      rules: {
        subjectName: [
          { required: true, message: "学科名称不能为空", trigger: "blur" },
          { max: 20, message: "学科名称不能超过20个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getSubjectList();
  },
  methods: {
    // 权限校验
    checkPermi,
    /** 查询学科列表 */

    async getSubjectList() {
      try {
        this.loading = true;
        let { data } = await listSubject(this.queryParams);
        this.subjectList = data.records;
        this.total = data.total;
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.log(error);
        this.$modal.error("获取学科列表失败");
      }
    },
    /** 获取所属试题 */
    async selectQuestionList() {
      try {
        let { data } = await getQuestionBySubjectId(this.questionListPage);
        this.questionList = data.records;
        this.questionListPage.total = data.total;
      } catch (error) {
        this.loading = false;
        console.log(error);
      }
    },
    /** 打开抽屉窗口并设置查询条件 */
    openDrawer(row) {
      this.questionListPage.subjectId = row.subjectId;
      this.selectQuestionList();
      this.drawerVisible = true;
    },
    /** 查看所属该学科的试题分页 */
    currentChange(e) {
      this.questionListPage.pageNum = e;
      this.selectQuestionList();
      console.log("currentChange", e);
    },
    sizeChange(e) {
      this.questionListPage.pageSize = e;
      this.selectQuestionList();
      console.log("sizeChange", e);
    },
    /**  取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        subjectId: null,
        subjectName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getSubjectList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.subjectId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学科";
    },
    /** 更改学科状态 */
    async handleStatus(row) {
      try {
        await updateSubjectStatus(row.subjectId, row.status);
        this.$modal.msgSuccess("状态修改成功");
      } catch (error) {
        console.log("error", error);
      }
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      try {
        this.reset();
        const response = await getSubject(row.subjectId);
        this.form = response.data;
        this.open = true;
        this.title = "修改学科";
      } catch (error) {
        console.log("error:", error);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.subjectId != null) {
            updateSubject(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getSubjectList();
              })
              .catch((e) => {
                console.log(e);
                this.$modal.msgSuccess("修改失败");
              });
          } else {
            addSubject(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getSubjectList();
              })
              .catch((e) => {
                console.log(e);
                this.$modal.msgSuccess("新增失败");
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let subjectIds = this.ids.length == 0 ? [row.subjectId] : this.ids;

      console.log("subjectIds", subjectIds);
      this.$modal
        .confirm('是否确认删除学科编号为"' + subjectIds + '"的数据项？')
        .then(function () {
          return delSubject(subjectIds);
        })
        .then(() => {
          this.getSubjectList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "exam/subject/export",
        {
          ...this.queryParams,
        },
        `subject_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
.questionList {
  .page {
    display: flex;
    align-items: center;
    // background-color: yellowgreen;
    height: 5vh;
  }
  .questionItem {
    height: 80vh;
    overflow-y: auto;
  }
}
</style>
